# coding=utf-8
import os
import sys

from loguru import logger

from web.core.middlewares import get_request_id
from web.settings import settings

logger.remove()
# 参考
# https://justcode.ikeepstudying.com/2019/12/python-%E6%97%A5%E5%BF%97%E8%AE%B0%E5%BD%95%E6%96%B9%E6%A1%88-loguru-%E6%97%A5%E5%BF%97%E6%A8%A1%E5%9D%97-loguru%E6%A8%A1%E5%9D%97-logger%E6%97%A5%E5%BF%97/
# https://blog.csdn.net/weixin_41287692/article/details/109769477
# https://bleepcoder.com/cn/loguru/636231326/issue-while-adding-request-id-in-flask
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

log_file_path = os.path.join(BASE_DIR, "logs/{}_info.log".format(settings.PROJECT_NAME))
warning_file_path = os.path.join(
    BASE_DIR, "logs/{}_warning.log".format(settings.PROJECT_NAME)
)
err_log_file_path = os.path.join(
    BASE_DIR, "logs/{}_error.log".format(settings.PROJECT_NAME)
)
critical_log_file_path = os.path.join(
    BASE_DIR, "logs/{}_critical.log".format(settings.PROJECT_NAME)
)

format_str = (
    "[<green>{time:YYYY-MM-DD HH:mm:ss.SSS}</green>]-"
    "[<level>{level}</level>]-"
    "[<blue>{process}</blue>]-"
    "[<magenta>{extra[request_id]}</magenta>]-"
    "[<cyan>{file}</cyan>.<cyan>{name}</cyan>.<cyan>{function}</cyan>:<cyan>{line}</cyan>]"
    " <level>{message}</level>"
)

logger.add(sys.stdout, colorize=True, format=format_str)

logger.add(
    log_file_path,
    format=format_str,
    rotation="500 MB",
    encoding="utf-8",
    compression="zip",
    enqueue=True,
    catch=True,
)
logger.add(
    warning_file_path,
    format=format_str,
    rotation="500 MB",
    encoding="utf-8",
    level="WARNING",
    compression="zip",
    enqueue=True,
    catch=True,
    backtrace=True,
    diagnose=True,
)

logger.add(
    err_log_file_path,
    format=format_str,
    rotation="500 MB",
    encoding="utf-8",
    level="ERROR",
    compression="zip",
    enqueue=True,
    catch=True,
    backtrace=True,
    diagnose=True,
)
logger.add(
    critical_log_file_path,
    format=format_str,
    rotation="500 MB",
    encoding="utf-8",
    level="CRITICAL",
    compression="zip",
    enqueue=True,
    catch=True,
    backtrace=True,
    diagnose=True,
)
# 动态更新extra的字段, 也就是说每次记录日志的时候,extra中的request_id字段都更新当前使用get_request_id()函数获取的信息
logger = logger.patch(
    lambda record: record["extra"].update(request_id=get_request_id())
)
